package ref;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Mark
 * @date 2020/5/24 23:18
 * @description 使用反射创建对象
 */
public class RefNewClass {

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {

        // 获取类
        Class<?> aClass = Class.forName("ref.User");

        // 构造对象(无参构造器)
        System.out.println("aClass.newInstance() = " + aClass.newInstance());

        // 构造器创建对象
        Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(String.class, int.class, int.class);
        System.out.println("declaredConstructor = " + declaredConstructor.newInstance("Wang", 1, 100));

        // 反射获取方法(invoke激活 对象和值)
        User o = (User) aClass.newInstance();
        Method setName = aClass.getDeclaredMethod("setName", String.class);
        setName.invoke(o, "wang");
        System.out.println(o.getName());

        // 反射操作属性
        User o1 = (User) aClass.newInstance();
        Field name = aClass.getDeclaredField("name");

        // 不能直接操作属性(设置为true可以操作/默认为false(安全检测)
        name.setAccessible(true);
        name.set(o1, "wan");
        System.out.println(o1.getName());


    }


}
